import { Router2, first } from "../addons/router";
import {
  deleteStorage,
  getStorage,
  listStorageId,
  putStorage,
} from "../models/storage";
import { withAuth, withHost, withRoot, withRootW } from "../services/sercurity";
import { json, withContent, withParams } from "itty-router";

const router = Router2({ base: "/storages" });
export default { base: "/storages/*", handle: router.handle };

router.all("*", withParams, withContent);

router.get("/", withAuth, async ({ query }, { kv }) => {
  query.host = first(query.host);
  if (query.host !== undefined) {
    return json((await getStorage(kv, query.host)) ?? null);
  } else {
    return json(await listStorageId(kv));
  }
});

router.get("/:id", withRoot, async ({ params }, { kv }) => {
  return json((await getStorage(kv, params.id)) ?? null);
});

router.put("/", withHost, async ({ query, content }, { kv }) => {
  query.host = first(query.host)!;
  await putStorage(kv, query.host, content);
  return json(null);
});

router.delete("/:id", withRootW, async ({ params }, { kv }) => {
  await deleteStorage(kv, params.id);
  return json(null);
});
